layui.define(['jquery', 'jqelem', 'layer', 'form', 'tablebutton'], function (exports) {
    var $ = layui.jquery,
        app = layui.data('app'),
        form = layui.form,
        laytpl = layui.laytpl,
        toolbar = 'toolbar',
        tablebtn = layui.tablebutton,
        zzpUtils = function () {
        };

    /**
     * 格式化url
     * @param isApi
     * @param url
     * @returns {string}
     */
    zzpUtils.prototype.formatUrl = function (url) {
        return app.contextPath + url;
    };
    /**
     * table表格初始化
     * @param option
     * @returns {*}
     */
    zzpUtils.prototype.tableInit = function (option) {

        $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['zh-CN']);
        var elem = option.elem,
            _option = {
                //始终显示分页
                smartDisplay: false,
                //toolbar
                toolbar: '#toolbar',
                isApi: true,//自定义属性是否遵循api 版本
                isOperate: false,//是否开启操作工具条
                idField: 'id',
                method: 'post',
                dataType: 'json',
                sidePagination: 'server',
                pagination: true,//是否分页
                pageList: [10, 20, 30, 40],
                pageNumber: 1,
                pageSize: 10,
                showColumns: true,
                //是否切换card方式
                showToggle: false,
                //导出方式
                exportDataType: "all",
                //显示导出
                showExport: false,
                clickToSelect: true,
                maintainSelected: true,
                exportTypes: ['csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],  //导出文件支持: 'json', 'xml', 'png', 'csv', 'txt', 'sql'，'doc', 'excel', 'xlsx', 'pdf'
                Icons: 'glyphicon-export',
                showFooter: false,//	是否true显示列脚
                responseHandler: function (res) {//处理相应
                    return res;
                },
                onPostBody: option.onPostBody,
                // detailView: true,
                // detailFormatter: function (index, row) {
                //     return "这里还没有确定";
                // },
                cardView: false,//设置为 true将显示card视图，适用于移动设备。否则为table试图，适用于pc
                undefinedText: '-',//当数据为 undefined 时显示的字符
                // height: getHeight(),
                //queryParamsType: 'limit'//请求参数
                queryParamsType: 'limit===this.options.queryParamsType&&(i={search:i.searchText,sort:i.sortName,order:i.sortOrder},this.options.pagination&&(i.offset=this.options.pageSize===this.options.formatAllRows()?0:this.options.pageSize*(this.options.pageNumber-1),i.limit=this.options.pageSize===this.options.formatAllRows()?this.options.totalRows:this.options.pageSize, i.pageNumber=this.options.pageNumber))'//请求参数
            };
        option.url = utils.formatUrl(option.url);
        _option = $.extend(true, _option, option);//继承

        // _option.url = (_option.isApi) ? Tool.app.version + option.url : option.url;//url 路劲
        // _option.url = Tool.formatUrl(_option.isApi, _option.url);
        _option.queryParams = function (data) {//查询参数
            if (typeof option.queryParams === 'undefined') {
                data = {
                    'page': data.pageNumber,
                    'rows': data.pageSize
                }
                return data;
            } else if (typeof option.queryParams === 'function') {
                var _data = option.queryParams();
                // console.log(typeof _data);
                data = {
                    'page': data.pageNumber,
                    'rows': data.pageSize
                }
                if (data === 'undefined') {
                    _data = '';
                } else if (typeof _data === "string") {
                    _data = {
                        'data_': _data
                    };
                    // console.info(_data);

                } else if (typeof _data === "function") {

                    layui.hint().error("table queryParams 最好返回对象")
                } else if (typeof _data === "object") {
                    // console.log(_data);
                    // $.each(_data.name,function (i,item) {
                    //     console.log(item);
                    // })
                }
                // console.info(data);
                // data = $.extend(true, data, _data);
                //

                return $.extend(true, data, _data);
            }
        };
        if (_option.isOperate) {
            var columns = _option.columns
            // oThis = this;
            columns.push({
                field: 'operate_',
                title: '操作',
                formatter: _option.operateFormatter,
                events: _option.operateEvents
            });
        }
        // function getHeight() {
        //     return $(window).height() - ($(joyiHead).outerHeight(true) + $(joyiQuote).outerHeight(true)) - ($(joyiBody).outerHeight(true) - $(joyiBody).height()) - fiexHeight;
        // }

        $(window).resize(function () {
            // $(elem).bootstrapTable('resetView', {
            //     height: getHeight()
            // });
        });

        return $(elem).bootstrapTable(_option);
    }
    zzpUtils.prototype.table = function (options) {
        var _this = this;
        var _options = {
            tableField: 'id',
            operateFormatter: function (value, row, index) {
                var btnHtml = tablebtn.init({
                    type: 2,
                    temp: $("#function_tpl"),
                    functions: options.functions,
                    row: row,
                });
                // console.log(btnHtml);
                return btnHtml;
                /*                var tpl = $("#function_tpl").html();
                 laytpl(tpl).render({functions:options.functions,row:row});*/
            },
            operateEvents: {
                'click *[lay-event]': function (e, value, row, index) {
                    var oThis = $(this),
                        params = {
                            elem: e,
                            value: value,
                            row: row,
                            index: index,
                            event: $(oThis).attr('lay-event')
                        };
                    // console.log("点我啦");
                    layui.event(toolbar, 'click(*)', params);
                    // layui.event(this, toolbar, 'click(*)', params);
                }
            },
            onPostBody: function () {
                if (options.isOperate) {
                    var data = $(options.elem).bootstrapTable('getData');
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            var name=_options.tableField;
                            if(options.tableField!=undefined){
                                name=options.tableField;
                            }
                            tablebtn.tooltipster({
                                elem: $("#tooltip" + data[i][name])
                            });
                        }
                    }
                }
            }
        }
        _options = $.extend(true, _options, options);
        //初始化table
        return _this.tableInit(_options);
    };
    zzpUtils.prototype.refreshTable = function (option) {
        $(option).bootstrapTable('refresh');
    };
    zzpUtils.prototype.fullDialog = function (option) {
        var _option = {
            title: "标题",
            type: 2,
            content: "#",
            isFull: false
        }
        _option = $.extend(true, _option, option);//继承
        var _index = layui.layer.open({
            title: _option.title,
            type: _option.type,
            content: utils.formatUrl(_option.content),
            success: function (layero, index) {
                try {
                    _option.success(layero, index);
                } catch (e) {
                    console.log(e.message);
                }

            }, cancel: function (index, layero) {
                layui.layer.confirm('信息未保存是否关闭', {
                    btn: ['是', '否'],
                    anim: 6,
                    shade: 0,
                    closeBtn: 2,
                    icon: 3
                }, function (index) {
                    layer.close(index);
                    layer.close(_index);
                }, function (index) {
                    layer.close(index);
                });
                return false;
            }
        });
        setTimeout(function () {
            layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                tips: [1, '#3595CC']
            });
        }, 500)
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）

        $(window).resize(function () {
            $("#layui-layer" + _index).css({
                "width": $(document).width(),
                "height": $(document).height(),
                "top": "0px",
                "left": "0px"
            });
            //TODO 这里弹框内容高度变化还没有调整好回头在看
            $("#layui-layer-iframe" + _index).css({
                "width": $(document).width(),
                "height": $(document).height(),
                "top": "0px",
                "left": "0px"
            });
        });
        layui.layer.full(_index);
        return _index;
    }
    /**
     * 打开普通信息页面
     * @param option
     */
    zzpUtils.prototype.dialog = function (option) {
        var _option = {
            isApi: false
            , title: '标题'
            , type: 2
            , skin: 'layui-layer-demo'
            , offset: 'auto' //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
            , id: 'layerDemo'//防止重复弹出
            , content: '/'
            , resize: false
            // , btn: ['保存', '取消']
            , btnAlign: 'r' //按钮居中
            , shade: [0.8, '#393D49'] //不显示遮罩
            , closeBtn: 1//不显示关闭按钮
            , area: ['75%', '95%']
            , success: function (layero, index, body, iframe) {
                console.log(layero, index, body, iframe);
            }
            , yes: function (index, layero, body, iframe) {
                layer.msg('To do something');
                layer.close(index);
            }
            , end: function () {
            }
        };
        _option = $.extend(true, _option, option);
        var _index = top.layer.open({
            title: _option.title
            , type: _option.type
            , offset: _option.offset //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
            , id: _option.id//防止重复弹出
            , content: utils.formatUrl(_option.content)
            , btn: _option.btn
            , btnAlign: _option.btnAlign //按钮居中
            , shade: _option.shade //不显示遮罩
            , closeBtn: _option.closeBtn//不显示关闭按钮
            , area: _option.area
            , scrollbar: false
            , resize: _option.resize
            , success: function (layero, index) {
                var body = top.layer.getChildFrame('body', index);
                var iframe = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                _option.success(layero, index, body, iframe);
                $(document).on('keydown', function (e) {
                    if (e.keyCode == 27) {
                        top.layer.confirm('信息未保存是否关闭', {
                            btn: ['是', '否'],
                            anim: 6,
                            shade: 0,
                            closeBtn: 2,
                            icon: 3
                        }, function (index) {
                            top.layer.close(_index);
                            top.layer.close(index);
                        }, function (index) {
                            top.layer.close(_index);
                        });
                    }
                })
            }
            , yes: function (index, layero) {
                // layui.form.on('submit(*)', function (data) {
                //     alert(data);
                // });
                // layui.form.validate();
                var body = top.layer.getChildFrame('body', index);
                var iframe = window[layero.find('iframe')[0]['name']];
                _option.yes(index, layero, body, iframe);
                layer.close(index);

            }, btn2: function (data) {
                top.layer.confirm('信息未保存是否关闭', {
                    btn: ['是', '否'],
                    anim: 6,
                    shade: 0,
                    closeBtn: 2,
                    icon: 3
                }, function (index) {
                    top.layer.close(_index);
                    top.layer.close(index);
                }, function (index) {
                    top.layer.close(_index);
                });
                return false;
            },
            end: function () {
                _option.end();
            }
        });
        return _index;
    };
    /**
     * 信息提示框
     * @param option
     */
    zzpUtils.prototype.confirm = function (message, option) {
        var _option = {
            btn: ['是', '否'],
            anim: 5,
            shade: [0.8, '#393D49'],
            closeBtn: 2,
            icon: 3,
            yes: function (index) {
                if (typeof option == "function") {
                    option();
                }
                top.layer.close(index);
            },
            cancel: function (index) {
            }
        };
        _option = $.extend(true, _option, option);
        top.layer.confirm(message, {
            btn: _option.btn,
            anim: _option.anim,
            shade: _option.shade,
            closeBtn: _option.closeBtn,
            icon: _option.icon
        }, function (index) {
            _option.yes(index);
        }, function (index) {
            _option.cancel(index);
        });
    };
    /**
     * 提示信息
     * @param message
     * @param option
     */
    zzpUtils.prototype.msg = function (message, option) {
        var _option = {
            icon: 6,
            anim: 5,
            isParent: true,
            end: function () {
            }
        };
        _option = $.extend(true, _option, option);
        if (_option.isParent) {
            parent.layer.msg(message, _option, function () {
                _option.end();
            });
        } else {
            layer.msg(message, _option, function () {
                _option.end();
            });
        }

    };

    /**
     * 透明的确定弹框事件
     * @param option
     */
    zzpUtils.prototype.msgBtn = function (message, option) {
        var _option = {
            time: 0,
            btn: ['确定', '取消'],
            yes: function (index) {
                if (typeof option == 'function') {
                    option(index);
                }
                // layer.close(index);
            }
        };
        layer.msg(message, _option);
    };


    /**
     * 处理后台提交返回的数据
     * @param option
     * @returns {*}
     */
    zzpUtils.prototype.successMsg = function (option) {
        var msg = '';
        if (option.title != '' && option.title != null && option.title != undefined) {
            msg += option.title;
            if (option.message != '' && option.title != null && option.message != undefined) {
                msg += ' : ';
            }
        }
        if (option.type == 'success') {
            layer.msg(msg + option.message);
            if (option.data != undefined) {
                return option.data;
            } else {
                return true;
            }
        } else {
            layer.msg(msg + option.message, {icon: 2});
            return false;
        }
    };

    /**
     * 弹框  form 会变化的form   init layer 参数
     * @type {{form: null, init: zzpUtils.dialogBtn.init}}
     */
    zzpUtils.prototype.dialogBtn = {
        form: null,
        init: function (option) {
            var _option = {
                type: 1,
                isForm: false,//是否需要动态绑定form
                area: 'auto',
                //offset: 'top',
                maxmin: false,
                scrollbar: true,
                content: option.content,
                form: option.form,
                btn: ['确定', '取消'],
                icon: 1,
                skin: 'layer-ext-moon',
                shift: 1,
                zIndex: 50,
                /*            success: function (layero, index, body, iframe) {
                 console.log(layero, index, body, iframe);
                 },*/
                btn1: function (index, layero) {
                    var body;
                    var iframe;
                    if (option.subBtn != undefined) {
                        body = top.layer.getChildFrame('body', index);
                        iframe = window[layero.find('iframe')[0]['name']];
                    }
                    var formEle = null;
                    if (_option.isForm) {
                        option.beforSubmit(iframe);
                        formEle = zzpUtils.prototype.dialogBtn.form;
                    } else if (option.form != undefined) {
                        formEle = option.form;
                    }

                    if (formEle != null) {
                        var submitName;
                        var btn;
                        if (option.subBtn != undefined) {
                            submitName = option.subBtn;
                            formEle.append('<button hidden="hidden" id="' + submitName + '" lay-submit lay-filter="' + submitName + '"></button>');
                            btn = $("#" + submitName, iframe.document);
                        } else {
                            submitName = parseInt(Math.random() * 100) + "formSubmit"
                            formEle.append('<button hidden="hidden" id="' + submitName + '" lay-submit lay-filter="' + submitName + '"></button>');
                            form.on("submit(" + submitName + ")", function (data) {
                                zzpUtils.prototype.msgBtn("是否确定" + option.title, function (msgindex) {
                                    option.submit(index, msgindex, layero, data);
                                    $("#" + submitName).remove();
                                })
                                return false;
                            });
                            btn = $("#" + submitName);
                        }
                        btn.click();
                    } else {
                        zzpUtils.prototype.msgBtn("是否确定" + option.title, function (msgindex) {
                            option.submit(index, msgindex, layero);
                        });
                    }
                },
                btn2: function (index) {
                    layer.close(index);
                },
                cancel: function (index) {
                    layer.close(index);
                },
                end: function () {
                    if (option.clear != undefined) {
                        option.clear();
                    }
                }
            }
            _option = $.extend(true, _option, option);
            // console.log(_option);
            if (option.url != undefined) {
                _option.content = utils.formatUrl(option.url);
            }
            var diyLayer = layer.open(_option);
            return diyLayer;
        },
    };

    /**
     * ajax 请求
     * @param option
     */
    zzpUtils.prototype.action = function (option) {
        var _option = {
            isApi: true,
            url: '',
            type: 'post',
            async: true,
            data: {},
            timeout: 180000,
            contentType: 'application/json',
            dataType: 'json',
            success: function (data, textStatus, jqXHR) {
                option.success(data, textStatus, jqXHR);
            },
            error: function (xhr, textStatus) {
                layer.message("系统异常");
            }
        };
        _option = $.extend(true, _option, option);

        _option.url = utils.formatUrl(_option.url);
        $.ajax(_option);
    };
    /**
     * get 请求
     * @param isApi
     * @param url
     * @param callback
     */
    zzpUtils.prototype.get = function (isApi, url, callback) {
        $.get(url, callback);
    };

    /**
     * post 请求
     * @param isApi
     * @param url
     * @param data
     * @param callback
     */
    zzpUtils.prototype.post = function (isApi, url, data, callback) {
        $.post(url, data, callback);
    };
    /**
     * 通用工具提交时form表单所有数据加载
     * @param form
     */
    zzpUtils.prototype.getFormJson = function (form) {
        var o = {};
        var a = $(form).serializeArray();
        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    }
    /**
     * select2封装方法
     * @param option
     * @returns {*|{}}
     */
    zzpUtils.prototype.select2 = function (option) {
        var _option = {
            ajax: {
                url: utils.formatUrl(option.url),
                multiple: option.multiple != null ? option.multiple : false,
                dataType: 'json',
                type: 'POST',
                contentType: "application/json",
                data: function (params) {
                    var query = {
                        mc: params.term
                    };
                    return JSON.stringify(query);
                },
                processResults: function (data) {
                    var arr = new Array();
                    if (data) {
                        for (var i = 0; i < data.length; i++) {
                            arr.push({id: data[i].id, text: data[i].mc});
                        }
                    }
                    // Tranforms the top-level key of the response object from 'items' to 'results'
                    return {
                        results: arr
                    };
                },
                cache: true
            },
            minimumInputLength: 1,    //搜索框至少要输入的长度，此处设置后需输入才显示结果
            language: "zh-CN",         //中文
            placeholder: '请输入查询字段',
            allowClear: true
        }
        var elem = option.elem,
            _option = $.extend(this, _option, option);
        return $(elem).select2(_option);
    }

    /**
     * layui form编辑回填数据方法
     * @param jsonStr
     */
    zzpUtils.prototype.loadJsonDataToForm = function (jsonStr) {
        var _this = this;
        try {
            //var obj = eval("("+jsonStr+")");
            var obj = jsonStr;
            var key, value, tagName, type, arr;
            for (var x in obj) {
                key = x;
                value = obj[x];
                $("[name='" + key + "'],[name='" + key + "[]']").each(function () {

                    tagName = $(this)[0].tagName;
                    type = $(this).attr('type');
                    if (tagName == 'INPUT') {
                        if (type == 'radio') {
                            $(this).attr('checked', $(this).val() == value);
                            form.render('radio');
                        } else if (type == 'checkbox') {
                            arr = value.split(',');
                            for (var i = 0; i < arr.length; i++) {
                                if ($(this).val() == arr[i]) {
                                    $(this).attr('checked', true);
                                    break;
                                }
                            }
                            form.render('checkbox');
                        } else {
                            $(this).val(value);
                        }
                    } else if (tagName == 'SELECT' && $(this).attr("select2") == undefined || tagName == 'TEXTAREA') {
                        $(this).val(value);
                        form.render('select');
                    } else if (tagName == 'SELECT' && $(this).attr("select2") != undefined) {
                        _this.select2ReturnValue($(this), value);
                    }
                    // else if(tagName=='SELECT' && $(this).attr("show_select")!="undefined"){
                    //     alert(value);
                    //     //_this.select2ReturnValue($(this),value);
                    // }
                });
            }
        } catch (e) {
            alert("加载表单：" + e.message + ",数据内容" + JSON.stringify(jsonStr));
        }
    }
    /**
     * layui select封装一般用于数据字典
     * @param option
     */
    zzpUtils.prototype.select = function (option) {
        var _this = this;
        var obj = option.elem;
        this.action({
            url: option.url,
            type: "get",
            // data:{
            //     id:$("#userId").val()
            // },
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    $(obj).append("<option value='" + data[i].dictionaryid + "'>" + data[i].value + "</option>");
                }
                form.render('select');
            }, error: function (xhr, textStatus) {
                console.log(textStatus);
                console.log(xhr)
            }
        })
    }
    /**
     * select2单个或多个回显
     * @param $dom
     * @param value
     */
    zzpUtils.prototype.select2ReturnValue = function ($dom, value) {
        if ($dom.attr("multiple")) {
            $.each(value, function (index, val) {
                $dom.append(new Option(val.text, val.id, false, true));
            });
            $dom.trigger("change");
        } else {
            $dom.append(new Option(value.text, value.id, false, true));
            $dom.trigger("change");
        }


        // $dom.select2({
        //     data: [{id:"1cb83591663547e1b2a1f2b684a378f3",text:"小静测试001"}]
        // });
        // $dom.trigger({
        //     type: 'select2:select',
        //     params: {
        //         data: val
        //     }
        // });
        // $dom.trigger("change");
    };

    /**
     * ztree
     * @type {{init: zzpUtils.ztree.init}}
     */
    zzpUtils.prototype.ztree = {
        init: function (option) {
            var _option = {
                setting: {
                    view: {
                        showLine: false,
                        // showIcon:false,
                        // selectedMulti:false,
                        // dblClickExpand:false
                    },
                    data: {
                        simpleData: {
                            enable: true
                        }
                    }
                },
                elem: option.elem,
                data: option.data
            };
            if (option.url != undefined) {
                $.ajax({
                    url: option.url,
                    data: option.data,
                    type: option.type,
                    async: false,
                    success: function (msg) {
                        option.data = msg;
                    }
                });
            }
            _option = $.extend(true, _option, option);//继承
            // console.log(_option);
            return $.fn.zTree.init(option.elem, _option.setting, option.data);
        }
    };

    zzpUtils.prototype.notification = {
        permission: function () {
            var NotificationInstance = Notification || window.Notification;
            if (NotificationInstance) {
                if (window.Notification.permission != 'granted') {
                    window.Notification.requestPermission();
                }
            } else {
                console.log('你的浏览器不支持此特性，请下载谷歌浏览器试用该功能');
            }
        },
        show: function (msg, option) {
            var _option = {
                body: '测试',
                tag: '2ue',
                icon: '12',
                data: {},
                onshow: function (n) {
                    console.log('通知显示了!!');
                },
                onclick: function (e, n) {
                    console.log("你点人家干嘛!!");
                    window.open(option.url, '_blank');
                    n.close();
                },
                onclose: function () {
                    console.log("我被关了!!");
                },
                onerror: function (err) {
                    console.log('出错了，小伙子在检查一下吧');
                    throw err;
                }
            }
            _option = $.extend(true, _option, option);
            console.log(_option);
            var NotificationInstance = Notification || window.Notification;
            if (NotificationInstance) {
                //授权了
                if (window.Notification.permission === 'granted') {

                    const n = new NotificationInstance(msg, _option);
                    console.log("kaishi 谈了");
                    n.onshow = function () {
                        _option.onshow(n);
                    }
                    n.onclick = function (e) {
                        //可以直接通过实例的方式获取data内自定义的数据
                        //也可以通过访问回调参数e来获取data的数据
                        _option.onclick(e, n);
                    }
                    n.onclose = function () {
                        _option.onclose();
                    }
                    n.onerror = function (err) {
                        _option.onerror(err);
                    }
                    setTimeout(1000, function () {
                        n.close();
                    });
                    return n;
                } else {
                    NotificationInstance.requestPermission();
                    return;
                }
                ;
            } else {
                console.log('你的浏览器不支持此特性，请下载谷歌浏览器试用该功能');
            }
        }
    }
    window.socketObj;
    zzpUtils.prototype.webSocket = {
        init: function (option) {
            if (!window.socketObj) {
                if (typeof(WebSocket) == "undefined") {
                    console.log("您的浏览器不支持WebSocket");
                } else {
                    window.socketObj = new WebSocket("ws://localhost:8080" + utils.formatUrl("/websocket"));
                    //打开事件
                    window.socketObj.onopen = function () {
                        console.log("Socket 已打开");
                    };
                    //获得消息事件
                    window.socketObj.onmessage = function (msg) {
                        console.log(msg);
                        //发现消息进入    调后台获取
                        // option.onMessage(msg);
                    };
                    //关闭事件
                    window.socketObj.onclose = function () {
                        console.log("Socket已关闭");
                    };
                    //发生了错误事件
                    window.socketObj.onerror = function () {
                        console.log("Socket发生了错误");
                    }
                    $(window).unload(function () {
                        window.socketObj.close();
                    });
                }
                return window.socketObj;
            } else {
                window.socketObj.onmessage = function (msg) {
                    console.log(msg);
                    // option.onmessage(msg)
                }
            }
        },
        send: function (data) {
            window.socketObj.send(data);
        }
    }

    zzpUtils.prototype.outputXslx = function (option) {
        var ot = new Date().getTime();
        var oloaded=0;
        var _option = {
            url: '',
            type: 'POST',
            responseType: 'blob',
            Accept: 'application/json',
            ContentType: 'application/json',
            Charset: 'utf-8',
            isAsync: true,
            onLoadStart: function(evt){
                console.log("请求开始");
            },
            onLoad: function () {
                console.log("检查了检查了");
                if (xhr.status == 200) {
                    layer.msg("导出成功",{icon: 6});
                    var name = xhr.getResponseHeader("Content-disposition");
                    name = decodeURI(name);
                    var filename = name.substring(20, name.length);
                    var blob = new Blob([xhr.response], {type: 'text/xls'});
                    var csvUrl = URL.createObjectURL(blob);
                    var link = document.createElement('a');
                    link.href = csvUrl;
                    link.download = filename;
                    link.click();
                }
            },
            //上传进度条
            upload: {
                onprogress: function (evt) {
                    // event.total是需要传输的总字节，event.loaded是已经传输的字节。如果event.lengthComputable不为真，则event.total等于0
                    if (evt.lengthComputable) {//
                        //progressBar.max = evt.total;
                        //progressBar.value = evt.loaded;
                        console.log("上传",Math.round(evt.loaded / evt.total * 100) + "%");
                    }

                    // var time = document.getElementByIdx_x("time");
                    var nt = new Date().getTime();//获取当前时间
                    var pertime = (nt - ot) / 1000; //计算出上次调用该方法时到现在的时间差，单位为s
                    ot = new Date().getTime(); //重新赋值时间，用于下次计算

                    var perload = evt.loaded - oloaded; //计算该分段上传的文件大小，单位b
                    oloaded = evt.loaded;//重新赋值已上传文件大小，用以下次计算

                    //上传速度计算
                    var speed = perload / pertime;//单位b/s
                    var bspeed = speed;
                    var units = 'b/s';//单位名称
                    if (speed / 1024 > 1) {
                        speed = speed / 1024;
                        units = 'k/s';
                    }
                    if (speed / 1024 > 1) {
                        speed = speed / 1024;
                        units = 'M/s';
                    }
                    speed = speed.toFixed(1);
                    //剩余时间
                    var resttime = ((evt.total - evt.loaded) / bspeed).toFixed(1);
                    console.log('，速度：' + speed + units + '，剩余时间：' + resttime + 's');
                    if (bspeed == 0)
                        console.log('上传已取消');
                }
            },
            //下载进度条
            onprogress: function (evt) {
                console.log("下载",evt.loaded,evt.total);
                // event.total是需要传输的总字节，event.loaded是已经传输的字节。如果event.lengthComputable不为真，则event.total等于0
                if (evt.lengthComputable) {//
                    //progressBar.max = evt.total;
                    //progressBar.value = evt.loaded;
                    console.log(Math.round(evt.loaded / evt.total * 100) + "%");
                }

                // var time = document.getElementByIdx_x("time");
                var nt = new Date().getTime();//获取当前时间
                var pertime = (nt - ot) / 1000; //计算出上次调用该方法时到现在的时间差，单位为s
                ot = new Date().getTime(); //重新赋值时间，用于下次计算

                var perload = evt.loaded - oloaded; //计算该分段下载的文件大小，单位b
                oloaded = evt.loaded;//重新赋值已上传文件大小，用以下次计算

                //上传速度计算
                var speed = perload / pertime;//单位b/s
                var bspeed = speed;
                var units = 'b/s';//单位名称
                if (speed / 1024 > 1) {
                    speed = speed / 1024;
                    units = 'k/s';
                }
                if (speed / 1024 > 1) {
                    speed = speed / 1024;
                    units = 'M/s';
                }
                speed = speed.toFixed(1);
                //剩余时间
                var resttime = ((evt.total - evt.loaded) / bspeed).toFixed(1);
                console.log('，速度：' + speed + units + '，剩余时间：' + resttime + 's');
            },
            onerror: function(){
                layer.msg('请求失败');
            }
        }

        _option = $.extend(true, _option, option);
        _option.url = utils.formatUrl(_option.url);
        var xhr = new XMLHttpRequest();
        xhr.open(_option.type, _option.url, _option.isAsync);
        xhr.responseType =  _option.responseType;
        xhr.setRequestHeader('Accept', _option.Accept);
        xhr.setRequestHeader('Content-Type', _option.ContentType);
        xhr.setRequestHeader('Charset', _option.Charset);
        xhr.onLoadStart = _option.onLoadStart;
        xhr.onprogress = _option.onprogress;
        xhr.upload.onprogress = _option.upload.onprogress;
        xhr.onload =  _option.onLoad;
        /*将条件查询和ids传到后台*/
        xhr.send(_option.data);
        return xhr;
    }

    var utils = new zzpUtils();
    /**
     *暴露接口
     */
    exports("zzpUtils", utils);
});